package com.gopay.bis.nucc.check.operation;

import com.gopay.bis.nucc.expay.operation.AesEncryptUtils;
import com.gopay.bis.nucc.expay.operation.CertificateCoder;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.exception.GopayException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import java.io.*;

/**
 * Created by zhoutong on 2017/9/1.
 */
public class CheckBillUtils {

    /**
     * 私钥解密
     * @param data
     * @param privateKeyPath
     * @return
     * @throws GopayException
     */
    public static String decode(String data, String privateKeyPath) throws GopayException {
        try{
            byte[] decryptByte = CertificateCoder.decryptByPrivateKey(Base64.decodeBase64(data),privateKeyPath);
            return StringUtils.newStringUtf8(decryptByte);
        }catch(Exception e){
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6076);
        }
    }

    /**
     * 对称解密文件
     * @param localFile
     * @param decryptFileName
     * @param key
     * @return
     * @throws Exception
     */
    public static String decodeFile(String localFile, String decryptFileName, String key) throws Exception{
        File encryptFile = null;
        File decryptFile = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        CipherOutputStream cipherOutputStream = null;
        try {
            encryptFile = new File(localFile);
            decryptFile = new File(decryptFileName);
            //获取对称密钥
            Cipher cipher = AesEncryptUtils.initAESCipher(StringUtils.getBytesUtf8(key));
            inputStream = new FileInputStream(encryptFile);
            outputStream = new FileOutputStream(decryptFile);
            cipherOutputStream = new CipherOutputStream(outputStream, cipher);
            byte [] buffer = new byte [1024];
            int r;
            while ((r = inputStream.read(buffer)) >= 0) {
                cipherOutputStream.write(buffer, 0, r);
            }
            cipherOutputStream.close();
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != outputStream) {
                outputStream.close();
            }
            if (null != cipherOutputStream) {
                cipherOutputStream.close();
            }
        }
        return decryptFileName;
    }
}
